package com.maserb.monitor.service.system_manage.impl;

import com.maserb.monitor.entity.DataDictionaryEntity;
import com.maserb.monitor.entity.DataDictionaryItemEntity;
import com.maserb.monitor.repository.DataDictionaryItemRepository;
import com.maserb.monitor.repository.DataDictionaryRepository;
import com.maserb.monitor.service.base.impl.JpaSpecificationServiceImpl;
import com.maserb.monitor.service.system_manage.DataDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class DataDictionaryServiceImpl extends JpaSpecificationServiceImpl<DataDictionaryRepository,
        DataDictionaryRepository, DataDictionaryEntity, String>
        implements DataDictionaryService {

    @Autowired
    DataDictionaryItemRepository itemRepository;

    @Override
    public Page<DataDictionaryEntity> findAll(Pageable pageable, String name) {
        return this.findAll(new Specification<DataDictionaryEntity>() {
            @Override
            public Predicate toPredicate(Root<DataDictionaryEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path<String> pathName = root.get("name");

                ArrayList<Predicate> list = new ArrayList<Predicate>();
                if (!StringUtils.isEmptyOrWhitespace(name)) {
                    list.add(criteriaBuilder.and(criteriaBuilder.like(pathName, "%" + name + "%")));
                }
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        }, pageable);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(DataDictionaryEntity entity, List<DataDictionaryItemEntity> itemList) {
        if (entity.getId() != null) {
            List<DataDictionaryItemEntity> items = this.findOne(entity.getId()).getItems();
            itemRepository.deleteAll(items);
        }
        itemRepository.saveAll(itemList);
        this.save(entity);
    }
}